package com.maiji.cloud.listener;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.maiji.cloud.entities.shopingmall.ShopingOrder;
import com.maiji.cloud.service.ShopingOrderService;
import com.maiji.cloud.utils.CommonIntValueEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class MyListener implements ApplicationListener<ApplicationReadyEvent> {

    // 定时取消订单任务调度
    public static final Timer AUTOCANCELORDERTIMER = new Timer();
    public static final Long AUTOPUSHMINUTES = 10L; // 定时推送时间
    public static final Long AUTOCANCELORDERMINUTES = 60*24L; // 定时取消订单时间

    @Autowired
    private ShopingOrderService shopingOrderService;
    @Autowired
    private MaijiTask maijiTask;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        // 定时取消订单
        if (shopingOrderService != null) {
            EntityWrapper<ShopingOrder> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("status", CommonIntValueEnum.SHOPPING_ORDER_STATUS_STAY_PAY.getValue());
            List<ShopingOrder> shopingOrders = shopingOrderService.selectList(entityWrapper);
            for (ShopingOrder shopingOrder: shopingOrders) {
                Long milliseconds = new Date().getTime() - shopingOrder.getCreateDate().getTime();
                Long timing = TimeUnit.MINUTES.toMillis(AUTOCANCELORDERMINUTES);
                Long delay = milliseconds < timing ? (timing - milliseconds) : 0;
                AUTOCANCELORDERTIMER.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            maijiTask.TimingCancelOrderTask(shopingOrder.getUuId(), AUTOCANCELORDERMINUTES);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, delay);
            }
        }
    }

}
